package org.example.concurrentUtils;

import lombok.extern.slf4j.Slf4j;
import org.example.utils.Sleeper;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 循环栅栏 测试类
 * @author ZhengDp
 * @Date 2023/2/20 22:37
 */
@Slf4j(topic = "c.CyclicBarrierTest")
public class CyclicBarrierTest {
    public static void main(String[] args) {
        ExecutorService service = Executors.newFixedThreadPool(2);

        CyclicBarrier barrier = new CyclicBarrier(2,() -> {
            // 当await恢复运行时，会执行该方法
            log.info("task1 , task2 finish ...");
        });
        for (int i = 0 ; i < 3 ; i ++ ) {
            service.submit(() -> {
                log.info("task1 begin ... ");
                Sleeper.sleep(1000);
                try {
                    barrier.await(); // 让初始计数 -1 ==> 计数不为0，线程阻塞
                } catch (InterruptedException | BrokenBarrierException e) {
                    throw new RuntimeException(e);
                }
            });

            service.submit(() -> {
                log.info("task2 begin ... ");
                Sleeper.sleep(2000);
                try {
                    barrier.await(); // 让初始计数 -1 ==> 计数不为0，线程阻塞
                } catch (InterruptedException | BrokenBarrierException e) {
                    throw new RuntimeException(e);
                }
            });
        }
        service.shutdown();
    }
}
